package com.bit.bit_forum.service.impl;

import com.bit.bit_forum.common.AppResult;
import com.bit.bit_forum.common.ResultCode;
import com.bit.bit_forum.dao.MessageMapper;
import com.bit.bit_forum.dao.UserMapper;
import com.bit.bit_forum.exception.ApplicationException;
import com.bit.bit_forum.model.Message;
import com.bit.bit_forum.model.User;
import com.bit.bit_forum.service.IMessageService;
import com.bit.bit_forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl implements IMessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private UserMapper userMapper;
//    发送站内信
    @Override
    public void create(Message message) {
        if(message==null || message.getPostUserId()==null
                || message.getReceiveUserId()==null
                || StringUtil.isEmpty(message.getContent())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //对 接收者用户身份 校验:
        User receiveUser = userMapper.selectByPrimaryKey(message.getReceiveUserId());
        if(receiveUser ==null || receiveUser.getDeleteStat()==1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //设初值:
        message.setState((byte)0);
        message.setDeleteStat((byte)0);
//        这个获取到的时间比当前时间要晚8小时
//        Date date = new Date();
        //矫正时间:
        // 直接在Instant上增加8小时，再转回Date
        Date date = Date.from(
                Instant.now().plus(8, ChronoUnit.HOURS)
        );
        message.setCreateTime(date);
        message.setUpdateTime(date);
        //插入数据库中:
        int n = messageMapper.insertSelective(message);
        if(n!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public Integer selectUnReadCount(Long receiveUserId) {
        //参数校验:
        if(receiveUserId==null || receiveUserId<=0){
            log.warn(ResultCode.FAILED_PASSWORD_ERROR.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(receiveUserId);
        //对用户身份校验:
        if(user==null || user.getDeleteStat()==1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        int n = messageMapper.selectUnReadCount(receiveUserId);
        return n;
    }

    @Override
    public List<Message> selectMessageList(Long userId) {
        //参数校验:
        if(userId==null || userId<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        List<Message> messages = messageMapper.selectMessageList(userId);
        return messages;
    }

    @Override
    public void updateStateById(Long id, Byte state) {
        //1.非空检验: state 0:未读,1:已读 2:已回复
        if(id==null || id<=0 || state<0 || state>2){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Message updateMessage = new Message();
        updateMessage.setId(id);
        updateMessage.setState(state);
        int n = messageMapper.updateByPrimaryKeySelective(updateMessage);
        if(n!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public Message selectById(Long id) {
        if(id==null || id<0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Message message = messageMapper.selectByPrimaryKey(id);
        return message;
    }

    @Override
    @Transactional //打包起来,要不全部通过,要不回滚数据
    public void reply(Long replyId, Message message) {
        //1.非空检验:
        if(replyId==null || replyId<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Message exisMessage = messageMapper.selectByPrimaryKey(replyId);
        if(exisMessage==null || exisMessage.getDeleteStat()==1){
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS));
        }
//        更新回复站内信的状态为 已回复:
        updateStateById(replyId,(byte)2);
        //将回复的站内信数据写入数据库
        create(message);
    }
}
